#! /usr/bin/env python
# -*- coding: utf-8 -*-

# *************************************************************
#     Filename @  write_error.py
#       Author @  Huoty
#  Create date @  2016-07-11 11:34:30
#  Description @
# *************************************************************

from tornado import httpserver, ioloop, web


class Application(object):
    def __init__(self):
        self.app = web.Application(self.init_handlers())

    def init_handlers(self):
        handlers = []
        handlers.append((r"/", IndexHandler))
        return handlers

    def start(self, port=8000, host="127.0.0.1"):
        http_server = httpserver.HTTPServer(self.app)
        http_server.listen(port, host)
        print("* Running on http://%s:%d/" % (host, port))
        ioloop.IOLoop.instance().start()


class IndexHandler(web.RequestHandler):
    def get(self):
        greeting = self.get_argument("greeting", "Hello")
        self.write(greeting + ", friendly user!")

    def write_error(self, status_code, **kwargs):
        self.write("Gosh darnit, user! You caused a %d error." % status_code)

# Script starts from here

if __name__ == "__main__":
    from tornado.options import options, define, parse_command_line
    define("port", default=8000, help="run on the given port", type=int)
    parse_command_line()

    app = Application()
    app.start(options.port)

